import {myAjax} from './AjaxBox.js'
import { ajax01 } from './AjaxBox.js'

// 轮播图的设置
//获取事件源
const imgBox=document.querySelector('.imgBox')
const imgData=[
    {url:'./images/imgPlay01.webp'},
    {url:'./images/imgPlay02.webp'},
    {url:'./images/imgPlay03.jpg'},
    {url:'./images/imgPlay04.webp'},
    {url:'./images/imgPlay05.webp'},
]
let i=0
//轮播图设计
//自动播放

let num01=setInterval(function(){
    i++
    i=i>imgData.length-1?0:i
    imgBox.style.background=`no-repeat center/cover url(${imgData[i].url})`
    document.querySelector('.dotBox .active').classList.remove('active')
    // document.querySelector(`.dotBox li:nth-child(${i+1})`).classList.add('active')
    document.querySelector(`.dotBox li:nth-child(${i+1})`).classList.add('active')
},1000)
//鼠标经过轮播图暂停，并显示左右箭头,可进行左右播放，离开时恢复自动播放
//图片与圆点关系复用函数
function imgDot() {
    imgBox.style.background=`no-repeat center/cover url(${imgData[i].url})`
    // 移除当前激活的点的active类，以取消其激活状态
    document.querySelector('.dotBox .active').classList.remove('active')
    // 为当前图片对应的点添加active类，以标记为激活状态
    // 使用模板字符串动态选择第i+1个li元素
    document.querySelector(`.dotBox li:nth-child(${i+1})`).classList.add('active')
}

const icon=document.querySelectorAll('.icon')
imgBox.addEventListener('mouseenter',function(){
    icon[0].style.display='block'
    icon[1].style.display='block'
    clearInterval(num01)
})
imgBox.addEventListener('mouseleave',function(){
    icon[0].style.display='none'
    icon[1].style.display='none'
    num01=setInterval(function(){
        i++
        i=i>imgData.length-1?0:i
        imgBox.style.background=`no-repeat center/cover url(${imgData[i].url})`
        imgDot()
    },1000)
})
//左右箭头点击事件
const leftGo=document.querySelector('.imgLeftGo')
const rightGo=document.querySelector('.imgRightGo')

rightGo.addEventListener('click',function(){
    i++
    i=i>imgData.length-1?0:i
    imgDot()
})
leftGo.addEventListener('click',function() {
    i--
    i=i<0?imgData.length-1:i
    imgDot()
//     const dotLis=document.querySelectorAll('.dotBox li')
//     console.log(dotLis)
})
//圆点点击事件
const dotLis=document.querySelectorAll('.dotBox li')
dotLis.forEach(function(item,index){
    item.addEventListener('click',function(){
        i=index
        imgDot()
    })
})

/* ===================================文章榜渲染===================================== */
const articleList=[]

//获取top榜数据
myAjax({
    url:'http://43.136.111.27:8086/article/top',
    params : {
        current: 1,
        size : 5
    }
}).then(res=>{
    // console.log(res.data.records)
    res.data.records.forEach(item=>{
        articleList.push(item)
    })
    // console.log(articleList[0].articleId)
    const containerMainRight02Content=document.querySelectorAll('.containerMainRight02Content')
    containerMainRight02Content.forEach(e=>{
        e.innerHTML=articleList.map((item,index)=>{
       
            return `
                    <div><span>${index+1}</span><span>${item.title}</span></div>
                `
           }).join('')
    })
    
})
/* ==============================中间推荐文章渲染========================================= */
const articleList02=[]
const textBody=document.querySelector('.textBody')
//获取推荐文章数据
myAjax({
    url : 'http://43.136.111.27:8086/article/top',
    params : {
        current : 1,
        size : 12
    }
}).then(res=>{
    // console.log(res.data.records)
    res.data.records.forEach(item=>{
        articleList02.push(item)

    })
    // console.log(articleList02)
   
    textBody.innerHTML = articleList02.map((item,index)=>{
        return `
            <div class="textBodyArticleBox" data-id="textBox">
                    <div class="textBodyArticleContent">
                        <div>${item.title}</div>
                        <div>${item.summary}</div>
                        <div>
                            ${item.articleCreateTime[0]}-${item.articleCreateTime[1]}-${item.articleCreateTime[2]}
                        </div>
                    </div>
                    <div class="textBodyArticleImg">
                        <img src="${item.coverUrl} " 
                        onerror="this.src='./images/guanggongwenchuang0926.png'"
                        alt="文章图片">
                    </div>
                </div>
        `
    }).join('')

    const textBodyArticleBox = document.querySelectorAll('[data-id="textBox"]')
    console.log(textBodyArticleBox)
    textBodyArticleBox.forEach(e => {
        e.addEventListener('click', () => {
        showBox('articleReadPageBox')
        
        })
    })

})

/* ------------------点击文章跳转到文章详情------------------------- */


/* ============================================================================== */
//经过使导航栏出现下划线

const navs=document.querySelectorAll('.container-head-middle .middleNav')
// console.log(navs)
for(let i=0;i<navs.length;i++) {
    navs[i].addEventListener('mouseenter',function() {
        // document.querySelector('.container-head-middle .active').classList.remove('active')
       this.classList.add('active')
    //  this.style.borderBottom='2px solid #1e80ff'
    })
}
//离开时恢复默认
for(let i=0;i<navs.length;i++) {
    navs[i].addEventListener('mouseleave',function() {
        this.classList.remove('active')
    })
}

/* ========================================================================== */
//推荐和最新的下划线的左右滚动

//运用事件委托
const twoNav=document.querySelector('.twoNav')
// console.log(twoNav);

const line=document.querySelector('.twoNav .line')
// console.log(line);
twoNav.addEventListener('click',function(e){
    // console.log(11);
    if(e.target.tagName === 'A') {
       //点击时，让下划线移动到对应的位置
        line.style.transform=`translateX(${e.target.offsetLeft}px)`
    }
    
}) 
/* ========================================================================= */
//控制主体部分三个模块以及顶部导航栏随着滚动而变化
//主体部分滑动到轮播图时，导航栏消失
const containerHead=document.querySelector('.container-head')
const containerMain=document.querySelector('.containerMain')
// console.log(imgBox);
const containerMainLeft=document.querySelector('.containerMainLeft')
// console.log(containerMainLeft);
const containerMainRight=document.querySelector('.containerMainRight')
const containerMainRightScroll=document.querySelector('.containerMainRightScroll')
const containerMainRightBox=document.querySelector('.containerMainRightBox')
window.addEventListener('scroll',()=>{
    const windowTop=document.documentElement.scrollTop
    if(windowTop <= imgBox.offsetTop || windowTop <=700){
        // containerHead.style.display='fixed'
        containerHead.style.top= 0
      
    } else if (windowTop > imgBox.offsetTop && windowTop <= document.querySelector('.containerMainRight07').offsetTop){
        // containerHead.style.display='absolute'
        containerHead.style.top= '-100px'
        // containerMainLeft.style.display = 'stick'
        containerMainLeft.style.top = '2rem'
      
    }  
})
//右边滑动到底部时，只显示文章榜和作者榜，不然显示右边全部内容
window.addEventListener('scroll',()=>{
    const windowTop=document.documentElement.scrollTop
    if( windowTop >= 750 ){
        containerMainRight.style.display = 'none'
        containerMainRightScroll.style.display = 'block'
        containerMainRightBox.classList.add('containerMainRightBoxFixed')
    } else {
        containerMainRight.style.display = 'block'
        containerMainRightScroll.style.display = 'none'
        if( containerMainRightBox.classList.contains('containerMainRightBoxFixed'))
        containerMainRightBox.classList.remove('containerMainRightBoxFixed')
    }
})
/* ======================================================== */
//点击登录框，登录框出现，点击叉号，登录框消失
const loginBox=document.querySelector('.loginBox')
const login = document.querySelector('.registrationAndLoginPart02')
const containerBox = document.querySelector('.containerBox')
const loginBoxClose = document.querySelector('.loginBoxClose')
const popUpMain03=document.querySelector('.popUpMain03')
// console.log( document.querySelector('.popUpLogin'))

// console.log(container)
//点击登录，登录框出现
login.addEventListener('click',function(){
    // container.style.display='none'
    containerBox.classList.add('fixed')
    loginBox.style.zIndex='2'


})

//出现登录框时，主体部分不能滚动
export function displayLoinBox() {
   document.querySelector('.containerBox').classList.add('fixed')
    document.querySelector('.loginBox').style.zIndex = '2'
}


/* ============================yoyo弹窗设计======================================== */
//设置一个定时器，让yoyo弹窗在打开页面3秒后出现
//检测是否已经登录，如果登录，则不显示弹窗
let token = localStorage.getItem('token')
if(token) {
    document.querySelector('.popUpLogin').style.display='none'

} else {
    let timer = setTimeout(() => {
        document.querySelector('.popUpLogin').style.display='block'
    },3000)
   
}



//点击yoyo弹窗，登录框出现
popUpMain03.addEventListener('click',function(){
        containerBox.classList.add('fixed')
        loginBox.style.zIndex='2'
        document.querySelector('.popUpLogin').style.display='none'
})
//点击叉号，登录框消失
document.querySelector('.popUpMain01 img').addEventListener('click',function(){
    document.querySelector('.popUpLogin').style.display='none'
})
loginBoxClose.addEventListener('click',function(){
    // container.style.display='block'
    containerBox.classList.remove('fixed')
    loginBox.style.zIndex='-1'
    // document.querySelector('.popUpLogin').style.display='block'
})


/* ===============================登录成功 样式变化============================ */
// const loginBoxBtn02 = document.querySelector('.loginBoxBtn02')
//  loginBoxBtn02.addEventListener('click',function() {
//     if(timer) {
//         clearTimeout(timer)
//     }
// })


//经过铃铛时，出现消息列表，离开时，消息列表消失
const bell = document.querySelector('.registrationAndLoginPart02Img01')
bell.addEventListener('mouseenter',function(){
    document.querySelector('.registrationAndLoginPart02ImgBillBox').style.display='block'
})
bell.addEventListener('mouseleave',function(){
    document.querySelector('.registrationAndLoginPart02ImgBillBox').style.display='none'
})

//点击信息列表里的标题，下面导航栏对应的标题高亮
//获取信息列表每个li元素
const registrationAndLoginPart02ImgBillBoxLis=document.querySelectorAll('.registrationAndLoginPart02ImgBillBox li')
// console.log(registrationAndLoginPart02ImgBillBoxLis)
//获取导航栏每个自定义属性元素
const personalNavDivs = document.querySelectorAll('.personalNav div')
// console.log(personalNavDivs[0].dataset.id);
registrationAndLoginPart02ImgBillBoxLis.forEach((e,index) => {
    e.addEventListener('click',() => {
        personalNavDivs.forEach(ev => {
            //任意点一个li元素，出现个人主页，其他隐藏
            document.querySelector('.containerMain').style.display='none'
            document.querySelector('.popUpLogin').style.display='none'
            document.querySelector('.personalBox').style.display='block'
            document.querySelector('.myHomePageBox').style.display='none'
           //判断当前点击的li元素 下标+1 和导航栏每个div的自定义属性值是否相等
           if(index+1 == ev.dataset.id) {
               ev.style.color = '#1e80ff'
           } else {
               ev.style.color = '#000'
           }
        //    showBox('personalBox')
        })
    })
})

//点击导航栏每个div,这个div高亮，其他div不高亮
personalNavDivs.forEach(e => {
    e.addEventListener('click',() => {
        //先将所有div的字体颜色设置为黑色
        personalNavDivs.forEach(e => {
            e.style.color = '#000'
        })
        //再将当前点击的div字体颜色设置为蓝色
        e.style.color = '#1e80ff'
    })
    
})

//点击头像时，出现下拉菜单
// console.log(document.querySelector('.userBox'))

const userImg = document.querySelector('.registrationAndLoginPart02Img02')
userImg.addEventListener('click',function(){
    document.querySelector('.userBox').style.display='block'
})

//除了点击头像和下拉菜单外，下拉菜单消失
document.addEventListener('click',function(e){
    if(e.target !== document.querySelector('.registrationAndLoginPart02Img02 img')) {
        document.querySelector('.userBox').style.display='none'
    }
})


// 个人主页的导航栏 下划线 变化 
const myHomePagLeftMainNavDivs = document.querySelectorAll('.myHomePagLeftMainNav>div')
// console.log(myHomePagLeftMainNavDivs)
const myHomePagLeftMainNavLines = document.querySelectorAll('.myHomePagLeftMainNav>div>div')
//  console.log(myHomePagLeftMainNavLines)
//点击导航栏的时候 对应下划线出现
for(let i = 0; i < myHomePagLeftMainNavDivs.length - 1; i++) {
    myHomePagLeftMainNavDivs[i].addEventListener('click', function() {
        myHomePagLeftMainNavLines.forEach(function(item,index) {
            if (index == i) {
                item.style.display = 'block'
            } else {
                item.style.display = 'none'
            }
        })
    })
}
//点击头像下拉菜单中 我的主页 出现个人主页
const myPage = document.querySelector('#myPage')
// console.log(myPage)
myPage.addEventListener('click', function() {
    //其他页面隐藏
    // document.querySelector('.containerMain').style.display='none'
    // document.querySelector('.popUpLogin').style.display='none'
    // document.querySelector('.personalBox').style.display='none'
    //   document.querySelector('.personalDataBox').style.display='none'
    // document.querySelector('.myHomePageBox').style.display='flex'
    showBox('myHomePageBox')
})

//点击返回个人主页按钮，出现个人主页
const personalDataHeadReturnBtn = document.querySelector('.personalDataHead div')
personalDataHeadReturnBtn.addEventListener('click',function(){
    // document.querySelector('.containerMain').style.display='none'
    // document.querySelector('.popUpLogin').style.display='none'
    // document.querySelector('.personalBox').style.display='none'
    //   document.querySelector('.personalDataBox').style.display='none'
    // document.querySelector('.myHomePageBox').style.display='flex'
    showBox('myHomePageBox')
})

/* ======================退出登录后样式变化=============================== */

//点击退出登陆后，铃铛 和 用户头像消失，登录和注册按钮出现
const loginOut = document.querySelector('.userFuc02 div:last-child')
// console.log(loginOut)
loginOut.addEventListener('click',function(){
        document.querySelector('.registrationAndLoginPart02').style.display='flex'
        document.querySelector('.registrationAndLoginPart02_').style.display='none'


    //清空登录信息
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('email')
    localStorage.removeItem('password')

        alert('退出登录成功')
        //回到首页
       tagWebHome.click()
})




/* --------------------------------------------------------------------- */
//点击首页后，出现首页，其他隐藏
const tagWebHome = document.querySelector('.middleNav')
tagWebHome.addEventListener('click',function(){
    // document.querySelector('.containerMain').style.display='flex'
    // document.querySelector('.personalBox').style.display='none'
    //   document.querySelector('.personalDataBox').style.display='none'
    showBox('containerMain')
})




/* ------------------------------个人主页-------------------------------------------- */
//设置个人主页的入口
const userFuc02 = document.querySelector('.userFuc02 div:first-child')
userFuc02.addEventListener('click',function(){
    // document.querySelector('.containerMain').style.display='none'
    // document.querySelector('.popUpLogin').style.display='none'
    // document.querySelector('.personalDataBox').style.display='flex'
    showBox('personalDataBox')
})
const myHomePagLeftHeadBtn = document.querySelector('.myHomePagLeftHeadBtn')
myHomePagLeftHeadBtn.addEventListener('click',function(){
    // document.querySelector('.containerMain').style.display='none'
    // document.querySelector('.popUpLogin').style.display='none'
    // document.querySelector('.myHomePageBox').style.display='none'
    // document.querySelector('.searchPageBox').style.display='none'
    // document.querySelector('.personalDataBox').style.display='flex'
    showBox('personalDataBox')
})




const personalDataMainLeftDivs = document.querySelectorAll('.personalDataMainLeft div')
// console.log(personalDataMainLeftDivs)
//点击哪个哪个高亮
personalDataMainLeftDivs.forEach(e => {
    e.addEventListener('click',function() {
        personalDataMainLeftDivs.forEach(e => {
            e.classList.remove('divActive')
        })
        this.classList.add('divActive')
    })
})


const personalData = document.querySelector('.personalDataMainLeft div:first-child')
// console.log(accountSetting)

personalData.addEventListener('click',function() {
    document.querySelector('.personalDataMainRight').style.display='flex'
})







//填充兴趣标签
const interestTags = ['人工智能','区块链','软件设计与数据结构和算法','开发工具','网络与信息安全','移动开发'
    ,'大数据','AIGC','运维与研发效能','媒体','应用软件','编程语言','专业成长','前端','前沿技术','数据库','操作系统','硬件',
    '服务端','游戏','云计算','社交网络与平台'
]
//展示区
const interestTagsDisplay = document.querySelector('.interestTagsDisplay')

//标签区
const interestTagsBox = document.querySelector('.interestTagsBox ul')
// console.log(interestTagsBox)
//填充标签区
interestTags.forEach(e => {
    interestTagsBox.innerHTML += `<li class="interestLi" data-tag = "${e}"> ${e}</li>`
})

const selectedLis = [] //存放被选中的li
const interestLis = document.querySelectorAll('.interestLi') //获取所有li

//设置标签区li的点击事件，点击后，li的背景颜色改变，并且展示区出现该标签
// 再次点击，取消高亮并在展示区消失
interestLis.forEach(e => {
    e.addEventListener('click',function() {
            const tagName = this.dataset.tag
            // console.log(tagName)

            const index = selectedLis.indexOf(tagName)
            //检查是否被选中，即是否在selectedLis数组中
            if(index == -1) {
                //添加到selectedLis数组中
                selectedLis.push(tagName)

                //添加高亮
                this.classList.add('light')
                // getInterestTags()

                //渲染展示区
                renderSelectedTags()

            } else {
                //从selectedLis数组中移除
                selectedLis.splice(index,1)

                 //取消高亮
                 this.classList.remove('light')

                 //渲染展示区
                 renderSelectedTags()
            }
            // console.log(selectedLis)
    })
})

//渲染展示区
//渲染已选中的标签
function renderSelectedTags() {
    interestTagsDisplay.innerHTML = selectedLis
        .map(e => `<li class="displayLi" data-tag = "${e}">
             ${e}
             <span>×</span>
             </li>`)
        .join('')
    if(selectedLis.length === 0) {
        interestTagsDisplay.innerHTML = `
          <div class="displayLiCue">请从下列标签中至少选择一项</div>
        `
    }

    //为展示标签的x添加点击事件
    document.querySelectorAll('.displayLi span').forEach(e => {
        e.addEventListener('click',function() {
            const tagName = this.parentNode.dataset.tag
            removeSelectedTags(tagName)
        })
    })

}

//移除标签设置
function removeSelectedTags(tagName) {
    const index = selectedLis.indexOf(tagName)
    if(index != -1) {
        selectedLis.splice(index,1)
    }
    //同步取消高亮标签
    document.querySelector(`.interestLi[data-tag="${tagName}"]`)
    .classList.remove('light')

    renderSelectedTags()
}


/* ----------兴趣标签修改和渲染------------------------ */

// function getInterestTags() {
//     const interestTagsDs = document.querySelectorAll('.interestTagsBox .light')
//     const interestTags = []
//     interestTagsDs.forEach(e => {
//         interestTags.push(e.dataset.tag)
//     })
   
//     //把数组转换为字符串
//     const interestTagsStr = interestTags.join(' ')
//     console.log(interestTagsStr)

 
    
//     const keepButton = document.querySelector('.keepButton')
//     keepButton.addEventListener('click',function() {
//           // 发送请求，将兴趣标签传到后端
//         ajax01({
//             url : 'http://43.136.111.27:8086/user/refresh/info',
//             method : 'post',
//             data : {
//                 interests : `${interestTagsStr}`
//             }
//         }).then(res => {
//             console.log(res)
//         }).catch(err => {
//             console.log(err)
//         })
        
//     })
// }





















 export function showBox(box) {
    const dataBoxs = document.querySelectorAll('.container [data-box]')
    if(box == 'personalBox'){
        dataBoxs.forEach(e => {
            e.style.display = 'none'
        })
        document.querySelector(`[data-box="${box}"]`).style.display = 'block'
        document.querySelector('[data-box="loginBox]').style.zIndex = '-1'
    } 
     else {
        dataBoxs.forEach(e => {
            e.style.display = 'none'
        })
        document.querySelector(`[data-box="${box}"]`).style.display = 'flex'
         document.querySelector('[data-box="loginBox]').style.zIndex = '-1'
    }
    

}














































/* ==========================导入封装的ajax======================================= */


//测试是否导入成功
// myAjax ({
//     url : '/user/register',
//     method : 'post',
//     data : {
//         "email": "k5qgs254@hotmail.com",
//         "username": "岑伟",
//         "password": "M3e3lq3maLqrmKY"
//     }

// }).then(res => {
//     console.log(res)
// })

